package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.entity.Result;
import com.atguigu.service.MemberService;
import com.atguigu.service.ReportService;
import com.atguigu.service.SetmealService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Eric
 * @Create 2020-09-22  20:41
 * @Version project-workspace-0912
 **/
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    @RequestMapping("/getMemberReport")
    public Result getMemberReport()
    {
        //获取日历对象
        Calendar calendar = Calendar.getInstance();
        //存取前12个月的年和月
        calendar.add(Calendar.MONTH,-12);

        List<String> list = new ArrayList<>();
        for(int i=0;i<12;i++)
        {
            //自增1 按月份加入到日历对象中
            //第一个参数是月份           2019-10
            //第二个参数是自增数  +1     2019-11
            calendar.add(Calendar.MONTH,1);
            list.add(new SimpleDateFormat("yyyy-MM").format(calendar.getTime()));//calendar.getTime()获取当前存储的时间
        }

        //存到map中
        Map<String,Object> map = new HashMap<>();
        map.put("Months",list);//需要的12个月份
        //System.out.println("map = " + map);
        //查询数据库返回月份对应的会员注册数量
        List<Integer> memberCount = memberService.findMemberCountByMonth(list);
        map.put("memberCount",memberCount);
        //System.out.println("memberCount = " + memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }

    // 统计套餐预约人数占比（饼图）
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        /**
         * Result(flag,message,data)
         data = Map<String,Object>
         map
         key                                      value
         setmealNames                List<String>
         setmealCount                List<Map<String,Object>>
         key:value,name
         value:3                     尚硅谷三八节福利套餐
         */
        // 组织套餐名称+套餐名称对应的数据
        List<Map<String,Object>> list =  setmealService.findSetmealCount();

        Map<String, Object> map = new HashMap<>();
        map.put("setmealCount",list);
        // 组织套餐名称集合（格式：List<"尚硅谷三八节福利套餐","尚硅谷旅游套餐">）
        List<String> setmealNames = new ArrayList<>();


        for (Map<String, Object> m : list) {
            String name = (String) m.get("name");
            setmealNames.add(name);
        }

        map.put("setmealNames",setmealNames);

        return new Result(true,MessageConstant.QUERY_SETMEALLIST_SUCCESS,map);

    }

    // 运营数据统计（页面）
    @RequestMapping(value = "/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String,Object> map = reportService.getBusinessReportData();
            // 成功
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            // 失败！
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }

    //导出Excel表
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){

        try {
        //从远程服务reportService取出数据
        Map<String, Object> data = reportService.getBusinessReportData();

        //从map结果集中，取出返回结果
        String reportDate =(String) data.get("reportDate");
        Integer todayNewMember =(Integer) data.get("todayNewMember");
        Integer totalMember =(Integer) data.get("totalMember");
        Integer thisWeekNewMember =(Integer) data.get("thisWeekNewMember");
        Integer thisMonthNewMember =(Integer) data.get("thisMonthNewMember");
        Integer todayOrderNumber =(Integer) data.get("todayOrderNumber");
        Integer todayVisitsNumber =(Integer) data.get("todayVisitsNumber");
        Integer thisWeekOrderNumber =(Integer) data.get("thisWeekOrderNumber");
        Integer thisWeekVisitsNumber =(Integer) data.get("thisWeekVisitsNumber");
        Integer thisMonthOrderNumber =(Integer) data.get("thisMonthOrderNumber");
        Integer thisMonthVisitsNumber =(Integer) data.get("thisMonthVisitsNumber");
        List<Map> hotSetmeal =(List<Map>) data.get("hotSetmeal");

        //获得Excel模板文件的绝对路径
      String templateRealPath =  request.getSession().getServletContext().getRealPath("template")+ File.separator
                + "report_template.xlsx";


      //创建读取模板的Excel对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(templateRealPath)));
            XSSFSheet sheet1 = workbook.getSheetAt(0);//第一张表的位置

            XSSFRow row = sheet1.getRow(2);//第二行
            row.getCell(5).setCellValue(reportDate);

            row = sheet1.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);
            row = sheet1.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);
            row.getCell(7).setCellValue(thisMonthNewMember);

            row = sheet1.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);
            row.getCell(7).setCellValue(todayVisitsNumber);
            row = sheet1.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            row.getCell(7).setCellValue(thisWeekVisitsNumber);
            row = sheet1.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            row.getCell(7).setCellValue(thisMonthVisitsNumber);

            //热门套餐
            int rowNum = 12;
            for(Map map : hotSetmeal){//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet1.getRow(rowNum++);
                if(row!=null) {
                    row.getCell(4).setCellValue(name);//套餐名称
                    row.getCell(5).setCellValue(setmeal_count);//预约数量
                    row.getCell(6).setCellValue(proportion.doubleValue());//占比
                }
            }

            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            // 下载的数据类型（excel类型）
            response.setContentType("application/vnd.ms-excel");
            // 设置下载形式(通过附件的形式下载)
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();

            return null;
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL, e.getMessage());
        }
    }
}
